﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SwAddinHelpers.Contracts;
using SwAddinHelpers.Attributes;

namespace SwAddinHelpers.Base
{
    public static class extensions
    {
        public static IEnumerable<IExternalUserControl> OrderByPropertyPages(this IEnumerable<IExternalUserControl> externalControls)
        {
            List<IExternalUserControl> temp = externalControls.ToList<IExternalUserControl>();

            bool HasChanged = false;

            for (int i = temp.Count - 1; i >= 0; i--)
            {
                HostedAsPropertyPage[] attribs = (HostedAsPropertyPage[])temp[i].ExternalUserControl.GetType().GetCustomAttributes(typeof(HostedAsPropertyPage), false);

                if (attribs.Length > 0)
                {
                    IExternalUserControl c = temp[i];
                    temp.RemoveAt(i);
                    temp.Insert(0, c);
                    c = null;
                    HasChanged = true;
                }
            }

            if (HasChanged) externalControls = temp.AsEnumerable<IExternalUserControl>();
            temp = null;
            
            return externalControls;
        }
    }
}
